package com.wsc.wisdomchina.activitity.baseactivity;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.samton.floatWindow.FloatWindowService;
import com.samton.floatWindow.MyWindowManager;
import com.umeng.analytics.MobclickAgent;
import com.wsc.wisdomchina.Tools.AbPermissionUtils;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.Tools.Tools;
import com.wsc.wisdomchina.application.MyApplication;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.constant.Constant;
import com.wsc.wisdomchina.httpUtils.HttpHeadParams;
import com.wsc.wisdomchina.javaBean.IpMessageBean;
import com.wsc.wisdomchina.javaBean.RespIpObj;
import com.wsc.wisdomchina.javaBean.RespObj;
import com.wsc.wisdomchina.javaBean.StreetInfoListBean;
import com.wsc.wisdomchina.presenter.ContributorPresenter;

import java.util.List;

/**
 * 父类 baseActivity
 */
public class BaseFragmentActivity extends FragmentActivity implements ContributorView {

	private AMapLocationClient mLocationClient=null;
	private AMapLocationClientOption mLocationOption = null;
	private MyApplication myApplication;
	private ContributorPresenter contributorPresenter;
	private final String LOCATION_FLAG="LOCATION_FLAG";
	private final String IP_FLAG="IP_FLAGFragment";

	private HomeWatcherReceiver mHomeWatcherReceiver = null;
	private AMapLocationListener mLocationListener=new AMapLocationListener() {
		@Override
		public void onLocationChanged(AMapLocation amapLocation) {
			if (amapLocation != null) {
				if (amapLocation.getErrorCode() == 0) {
					String city= amapLocation.getCity();//城市信息
					String district=amapLocation.getDistrict();//城区信息
					String address=amapLocation.getAddress();
					myApplication.setLocationCity(city);
					myApplication.setLongitude(amapLocation.getLongitude());
					myApplication.setLatitude(amapLocation.getLatitude());
					myApplication.setLocationDistrict(district);
					myApplication.setLocationAddress(address);
//					HttpHeadParams.getInstance().setAddr(address);
					mLocationClient.stopLocation();
					contributorPresenter.getHomeFetchStreet(city,district,LOCATION_FLAG);
				}else {
					//定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
				}
			}
		}
	};


	@Override
	public void onLoadContributorStart(String flag) {

	}

	@Override
	public void onLoadContributorSuccess(String jsonString, String flag) {
		try {
			//发送验证码
			if (flag.equals(LOCATION_FLAG)) {
				RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
				String code=respObj.getCode();
				if(code.equals("200"))
				{
					String message=JsonTools.objectToJsonString(respObj.getMessage());
					List<StreetInfoListBean> listData=JsonTools.jsonStringToList(message,StreetInfoListBean.class);
					if(listData!=null &&listData.size()>0)
					{
						Tools.setSharedPreferencesStrings(Constant.SharePreferenceLocation,JsonTools.objectToJsonString(listData.get(0)),BaseFragmentActivity.this);
					}
				}
			}
			//获取IP地址
			else if(flag.equals(IP_FLAG))
			{
				RespIpObj respObj = JsonTools.jsonStringToObject(jsonString, RespIpObj.class);
				String code=respObj.getCode();
				if(code.equals("0"))
				{
					String jsonMessage=JsonTools.objectToJsonString(respObj.getData());
					IpMessageBean ipMessageBean=JsonTools.jsonStringToObject(jsonMessage,IpMessageBean.class);
					if(ipMessageBean!=null)
					{
						String Ip=ipMessageBean.getIp();
						if(Ip!=null)
						{
							myApplication.setIP(Ip);
							HttpHeadParams.getInstance().setIp(Ip);
							//中国
							String country=Tools.unicodeToString(ipMessageBean.getCountry());
							HttpHeadParams.getInstance().setCountry(country);
//							private String region;省份
							String region=Tools.unicodeToString(ipMessageBean.getRegion());
							HttpHeadParams.getInstance().setRegion(region);
//							private String city;城市
							String city=Tools.unicodeToString(ipMessageBean.getCity());
							HttpHeadParams.getInstance().setCity(city);
//							private String county;县
							String county=Tools.unicodeToString(ipMessageBean.getCounty());
							HttpHeadParams.getInstance().setCounty(county);
//							private String isp; 运营商
							String isp=Tools.unicodeToString(ipMessageBean.getIsp());
							HttpHeadParams.getInstance().setIsp(isp);
							myApplication.setLocationCity(city);
							if(county!=null && county.length()>0)
							{
								myApplication.setLocationDistrict(county);
								contributorPresenter.getHomeFetchStreet(city,county,LOCATION_FLAG);
							}
						}
					}
				}
			}
		} catch (Exception e) {

		}
	}

	@Override
	public void onLoadContributorComplete(String flag) {
	}

	@Override
	public void onLoadContributorError(String error,String flag) {

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		myApplication=(MyApplication) getApplication();
		myApplication.activities.add(this);
		contributorPresenter = new ContributorPresenter(this, BaseFragmentActivity.this);
		if(HttpHeadParams.getInstance().getImei()==null || HttpHeadParams.getInstance().toString().trim().isEmpty())
		{
			AbPermissionUtils.requestPermissionsResult(this, 1
					, new String[]{Manifest.permission.READ_PHONE_STATE,
					}
					, new AbPermissionUtils.OnPermissionListener() {
						@Override
						public void onPermissionGranted() {
							// 获取到imei
							String imei = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getDeviceId();
							HttpHeadParams.getInstance().setImei(imei);
						}

						@Override
						public void onPermissionDenied() {

						}
					});
		}

		if(myApplication.getLocationCity()==null && myApplication.getLocationDistrict()==null)
		{
			mLocationClient=new AMapLocationClient(getApplicationContext());
			mLocationClient.setLocationListener(mLocationListener);
			mLocationOption = new AMapLocationClientOption();
			mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
			mLocationOption.setLocationCacheEnable(false);
			mLocationClient.setLocationOption(mLocationOption);

			AbPermissionUtils.requestPermissionsResult(this, 1
					, new String[]{  Manifest.permission.ACCESS_COARSE_LOCATION,
							Manifest.permission.ACCESS_FINE_LOCATION,
							Manifest.permission.WRITE_EXTERNAL_STORAGE,
							Manifest.permission.READ_EXTERNAL_STORAGE,
							Manifest.permission.READ_PHONE_STATE}
					, new AbPermissionUtils.OnPermissionListener() {
						@Override
						public void onPermissionGranted() {
							//启动定位
							mLocationClient.startLocation();
						}

						@Override
						public void onPermissionDenied() {

						}
					});
		}

		//获取Ip
		String Ip=myApplication.getIP();
		if(Ip==null || TextUtils.isEmpty(Ip))
		{
			contributorPresenter.getMyIp(IP_FLAG);
		}
		registerReceiver();
	}
	private void registerReceiver() {
		mHomeWatcherReceiver = new HomeWatcherReceiver();
		IntentFilter filter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		registerReceiver(mHomeWatcherReceiver, filter);
	}
	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (myApplication != null) {
			myApplication.activities.remove(this);
		}
		if (mHomeWatcherReceiver != null) {
			unregisterReceiver(mHomeWatcherReceiver);
		}
	}

	public class HomeWatcherReceiver extends BroadcastReceiver {

		private static final String SYSTEM_DIALOG_REASON_KEY = "reason";
		private static final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

		@Override
		public void onReceive(Context context, Intent intent) {

			String intentAction = intent.getAction();
			Log.i("reciver", "intentAction =" + intentAction);
			if (TextUtils.equals(intentAction, Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
				String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
				Log.i("reciver", "reason =" + reason);
				if (TextUtils.equals(SYSTEM_DIALOG_REASON_HOME_KEY, reason)) {
					stopService(new Intent(getApplicationContext(), FloatWindowService.class));
					MyWindowManager.removeSmallWindow(BaseFragmentActivity.this);
				}
			}
		}
	}
}
